package com.qiandw

import com.mchange.v2.c3p0.ComboPooledDataSource
import com.qiandw.config.DemoMysqlConfig
import com.qiandw.spark.SparkContextFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.cache.annotation.EnableCaching
import org.springframework.cloud.client.discovery.EnableDiscoveryClient
import org.springframework.context.annotation.{Bean, EnableAspectJAutoProxy}
import org.springframework.web.client.RestTemplate
import org.springframework.web.servlet.config.annotation._

@EnableCaching
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = Array("com.qiandw"))
class AppConf extends WebMvcConfigurerAdapter {

  @Autowired
  var scf: SparkContextFactory = _

  @Autowired
  var demoCfg: DemoMysqlConfig = _

  @Bean(Array("simpleRestTemplate"))
  def restTemplate: RestTemplate = {
    new RestTemplate
  }

  @Bean(name = Array("demoDatasource"))
  @throws[Exception]
  def demoDatasource: ComboPooledDataSource = createDatasourceBean(demoCfg.driverClass, demoCfg.conStr, demoCfg.username, demoCfg.password)

  @throws[Exception]
  private def createDatasourceBean(driver: String, conStr: String, user: String, pwd: String) = {
    val ds = new ComboPooledDataSource
    ds.setDriverClass(driver)
    ds.setJdbcUrl(conStr)
    ds.setUser(user)
    ds.setPassword(pwd)
    ds.setAutoCommitOnClose(true)
    ds.setTestConnectionOnCheckin(true)
    ds
  }

}
